﻿/*----------------------------------------------------------------
           // Copyright (C) 2008 安华顺通(北京)科技有限公司
           // 版权所有。 
           //
           // 文件名：SysCompilerTable.cs
           // 文件功能描述：表编译功能。
           //
           // 
           // 创建标识：周玉偈20080916
           //
           // 修改标识
           // 修改描述：
           //
           // 修改标识：
           // 修改描述：
//----------------------------------------------------------------*/

#region UsingStatements

using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Windows.Forms;
using Microsoft.CSharp;
using RuleCode.ObjectTree;
using RuleCode.TemplateEngine;
using Util = RuleCode.ObjectTree.Util;
#endregion

namespace RuleCode.compiler
{
    internal class SysCompilerTable
    {
        private static SysCompilerTable sysCompilerTable;
        private static readonly string TablePath = Util.GetTablesPath +"\\";// Util.OTPath + "\\Module\\Tables\\";
        private static readonly string PartialTablePath = Util.GetPartialTablesPath + "\\";
        private static readonly string QueryPath =Util.GetQueriesPath +"\\";// Util.OTPath + "\\Module\\Queries\\";
        private static readonly string QueryDemoPath = Util.OTPath + "\\Templates\\单表标准模块_Query.cs";
        private static readonly string keyFile = "D:\\snk\\RuleCode.Query.snk";

        public static SysCompilerTable Instance
        {
            get
            {
                if (sysCompilerTable == null)
                {
                    sysCompilerTable = new SysCompilerTable();
                }
                return sysCompilerTable;
            }
        }
   
        private static readonly string toTablePath = Util.GetOutputTablePath();

        private static readonly string fromTablePath = Util.OTPath + "\\templates\\";
        private static readonly string templatePath = Util.OTPath + "\\templates\\";

        private static readonly string toQueryPath = Util.GetOutputQueryPath();

        public void compileTable2(SysTreeNode node)
        {
            Util.SetProerptyInSilent(node);
            node.ExpandAll();
            string NameSpace = Util.RootClassNameSpace+".Table";     
            string TableName = node.Text;
            // compile using template
            Template template1 = Template.FromString("tem", new StreamReader(fromTablePath + "Table.vm").ReadToEnd());
            TemplateManager template = new TemplateManager(template1);


            template.SetValue("NameSpace", NameSpace);

            template.SetValue("ClassName", TableName);
            template.SetValue("TableName", TableName);
            template.SetValue("Fields", node.Nodes[0].Nodes);
            template.SetValue("TableProperty", node.Property);



            StreamWriter o = new StreamWriter(toTablePath + TableName + ".Designer.cs", false);

            o.Write(template.Process());
            o.Close();

            //#region Query

            //template =TemplateManager.FromFile(templatePath + "Query.vm");

            //NameSpace = "RuleCode.Queries";
            //template.SetValue("NameSpace", NameSpace);

            //template.SetValue("ClassName", TableName);
            //template.SetValue("TableName", TableName);
          



            // o = new StreamWriter(toQueryPath + TableName + "_Query.cs", false);

            //o.Write(template.Process());
            //o.Close();

            //#endregion

            #region TableFields
            SysTreeNode tableFields = (SysTreeNode)node.Nodes[0];
            foreach (SysTreeNode tField in tableFields.Nodes)
            {
             //   Util.SetProerptyInSilent(tField);
             //   template = TemplateManager.FromFile(templatePath + "TableField.vm");

             //   NameSpace = "RuleCode.Table.TableField";
             //   template.SetValue("NameSpace", NameSpace);
             //   template.SetValue("FieldName", tField.Text);
             //   template.SetValue("ClassName", tField.Text);
             //   template.SetValue("TableName", TableName);
             //   PropertyInfo[] i = tField.Property.GetType().GetProperties();
             //object ii =   i[0].GetValue(tField.Property, null);

                
             //   template.SetValue("Property", tField.Property.GetType().GetFields());
                SysCompilerTableField.Instance.compileTableField(tField, node.Text);

               
            }
            #endregion


            //将编译 好的文件添加到项目中
            if (Util_DTE.IsAddToProjectAtCompiled)
                Util_DTE.AddGeneratedFileToProject(node, GenerateFileType.Table );
        }
        public void compileTable(SysTreeNode node)
        {
           
            #region 初始化环境

            string name = node.Text;
            string op;

            CodeCompileUnit CompileUnit = new CodeCompileUnit();
            CodeCompileUnit PartialCompileUnit = new CodeCompileUnit();
            //CompileUnit.AssemblyCustomAttributes.Add(new System.CodeDom.CodeAttributeDeclaration
            //    ("System.Reflection.AssemblyKeyFile", new System.CodeDom.CodeAttributeArgument(
            //    new System.CodeDom.CodePrimitiveExpression(keyFile)))); 
            Util.SetProerptyInSilent(node);

            CodeNamespace tableNameSpace = new CodeNamespace(SysDefalutNamespace.DefaultTableNameSpace);
            CodeNamespace patialTableNameSpace = new CodeNamespace(SysDefalutNamespace.DefaultTableNameSpace);
            CompileUnit.Namespaces.Add(tableNameSpace);
            PartialCompileUnit.Namespaces.Add(patialTableNameSpace);

            CodeTypeDeclaration table = new CodeTypeDeclaration(name);
            CodeTypeDeclaration partialTable = new CodeTypeDeclaration(name);

            //设置类的继承。
            table.IsClass = true;
            partialTable.IsClass = true;
            table.TypeAttributes = TypeAttributes.Public;
            partialTable.TypeAttributes = TypeAttributes.Public;
            table.IsPartial = true;
            partialTable.IsPartial = true;

            table.BaseTypes.Add("RuleCode.Common.Table");
            // 将类型加入到容器的类型集合中
            tableNameSpace.Types.Add(table);
            tableNameSpace.Imports.Add(new CodeNamespaceImport("System"));
            tableNameSpace.Imports.Add(new CodeNamespaceImport("System.Collections.Generic"));
            tableNameSpace.Imports.Add(new CodeNamespaceImport("System.Text"));
            tableNameSpace.Imports.Add(new CodeNamespaceImport("System.ComponentModel"));
            tableNameSpace.Imports.Add(new CodeNamespaceImport("System.Data"));
            tableNameSpace.Imports.Add(new CodeNamespaceImport("RuleCode.Common"));
            //tableNameSpace.Imports.Add(new CodeNamespaceImport("RuleCode.ExtendType"));
            //tableNameSpace.Imports.Add(new CodeNamespaceImport("RuleCode.Table.TableField"));
            tableNameSpace.Imports.Add(new CodeNamespaceImport("RuleCode.ObjectTree"));
            tableNameSpace.Imports.Add(new CodeNamespaceImport("System.Reflection"));
            tableNameSpace.Imports.Add(new CodeNamespaceImport(SysDefalutNamespace.DefaultTableFieldNameSpace));
            


            table.Comments.Add(new CodeCommentStatement("<summary>", true));
            table.Comments.Add(new CodeCommentStatement((node.Property as TableProperty).LabelText, true));
            table.Comments.Add(new CodeCommentStatement("</summary>", true));
            patialTableNameSpace.Types.Add(partialTable);
            partialTable.Comments.Add(new CodeCommentStatement("<summary>", true));
            partialTable.Comments.Add(new CodeCommentStatement((node.Property as TableProperty).LabelText, true));
            partialTable.Comments.Add(new CodeCommentStatement("</summary>", true));
            #endregion

            #region 函数

            //构造函数
            string constructorString0 = "       public " + name + "() : base() { InitTable(); }";
            string constructorString1 = "       public " + name + "(string cmdText) : base(cmdText) { InitTable(); }";
            string constructorString2 = "       public " + name +
                                        "(string cmdText, int count) : base(cmdText, count) { InitTable(); }";

            table.Members.Add(new CodeSnippetTypeMember(constructorString0));
            table.Members.Add(new CodeSnippetTypeMember(constructorString1));
            table.Members.Add(new CodeSnippetTypeMember(constructorString2));


            string findmethod = @"
      public static " + name + @" Find(string filter)
       {
           return ( " + name + @" )RuleCode.Common.Table.Find(filter, typeof( " + name + @" ));
       }

            ";

            string findSortMethod = @"
      public static " + name + @" Find(string filter,string sorting)
       {
           return ( " + name + @" )RuleCode.Common.Table.Find(filter,sorting ,typeof( " + name + @" ));
       }

            ";
            table.Members.Add(new CodeSnippetTypeMember(findmethod));
            table.Members.Add(new CodeSnippetTypeMember(findSortMethod));
            #endregion

            #region C# 定义属性

            //属性变量
            TableProperty tableProperty;
            tableProperty = (TableProperty)node.Property;
            //
            compileTableQuery(node.Text + "_Query", name, tableProperty.Label,node);


            op =
                @"
                    public override RuleCode.ObjectTree.TableProperty Property
                    {
                        get
                        {
                            if (this.property == null)
                                this.property = new RuleCode.ObjectTree.TableProperty();
                            ";

            #region C# 定义属性

            //定义属性类
            Type mytype = tableProperty.GetType();
            MemberInfo[] ms = mytype.FindMembers(MemberTypes.Property,
                                                 BindingFlags.Instance | BindingFlags.Public,
                                                 Type.FilterName, "*");
            foreach (MemberInfo m in ms)
            {
                foreach (Attribute att in m.GetCustomAttributes(true))
                {
                    if (att is DataMemberAttribute)
                    {
                        if (mytype.GetProperty(m.Name).GetValue(tableProperty, new Object[0]) is int)
                        {
                            op += " this.property." + m.Name +
                                  " = " + (mytype.GetProperty(m.Name).GetValue(tableProperty, new Object[0])) +
                                  " ; ";
                        }
                        else if (mytype.GetProperty(m.Name).GetValue(tableProperty, new Object[0]) is DateTime)
                        {
                            op += " this.property." + m.Name +
                                  " = Convert.ToDateTime (\"" +
                                  (mytype.GetProperty(m.Name).GetValue(tableProperty, new Object[0])) +
                                  "\") ; ";
                        }
                        else if (mytype.GetProperty(m.Name).GetValue(tableProperty, new Object[0]) is Boolean)
                        {
                            op += " this.property." + m.Name +
                                  " = Convert.ToBoolean (\"" +
                                  (mytype.GetProperty(m.Name).GetValue(tableProperty, new Object[0])) +
                                  "\") ; ";
                        }
                        else
                        {
                            op += " this.property." + m.Name +
                                  " = \"" + (string)mytype.GetProperty(m.Name).GetValue(tableProperty, new Object[0]) +
                                  "\" ; ";
                        }
                    }
                }
            }

            #endregion

            op +=
                @"
                                return this.property;
                            }
                            
                        }
                        ";
            table.Members.Add(new CodeSnippetTypeMember(op));

            #endregion

            #region 字段

            node.ExpandAll();
            //Note:Find方法有问题，
            TreeNode tempnode = node.Nodes.Find("Fields", false).First();
            TableFieldProperty tableFieldProperty;
            string fieldName;
            string edtName;
            tempnode.ExpandAll();
            //增加InitTable()函数，内容从丁余良的代码中抄的
            string initMember = @"
        protected override void InitTable()
        {
 base.InitTable();
";
            string thisstr =
                @"
        public override object this[string caption]
        {
            get
            {
                switch (caption )
                { 
                    case " + "\"RECID\": return RECID;" + "case " + "\"DATAAREAID\": return DATAAREAID;" + @"
";

            foreach (SysTreeNode tField in tempnode.Nodes)
            {
                Util.SetPropertyInSilent = true;
                Util.SetPropertyContent(tField);
                Util.SetPropertyInSilent = false;


                tableFieldProperty = (TableFieldProperty)tField.Property;
                fieldName = tableFieldProperty.Name;
                edtName = tableFieldProperty.ExtendedDataType;

                initMember += "this." + fieldName + " = new " + name + "_" + fieldName + "()  ;";
                initMember += "this." + fieldName + ".Table = this;";
                initMember += "this.AllFields.Add(\"" + fieldName + "\");";
                thisstr += "case  \"" + fieldName + "\"" + ":return " + fieldName + " ; ";

                SysCompilerTableField.Instance.compileTableField(tField, node.Text);

                //增加字段属性对应的私有变量
                CodeMemberField field = new CodeMemberField(name + "_" + fieldName, "_" + fieldName);
                field.Attributes = MemberAttributes.Private;
                table.Members.Add(field);
                //增加字段属性
                CodeMemberProperty fieldProperty = new CodeMemberProperty();
                fieldProperty.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                fieldProperty.Type = new CodeTypeReference(name + "_" + fieldName);
                fieldProperty.Name = fieldName;
                fieldProperty.Comments.Add(new CodeCommentStatement(" <summary> ", true));

                string commentString = fieldName + " " + tableFieldProperty.FieldType + "; ";
                if (tableFieldProperty.FieldType == "TEnum")
                {
                    if ((tableFieldProperty as TableFieldEnumProperty).EnumType != null && (tableFieldProperty as TableFieldEnumProperty).EnumType != "")
                        commentString += "  BaseEnum:" + (tableFieldProperty as TableFieldEnumProperty).EnumType;
                    else
                        commentString += "  BaseEnum:" + tableFieldProperty.ExtendedDataType;
                }
                else
                    commentString += "  ExtendDataType:" + tableFieldProperty.ExtendedDataType;

                fieldProperty.Comments.Add(new CodeCommentStatement(commentString, true));
                fieldProperty.Comments.Add(new CodeCommentStatement(" </summary> ", true));
                //fieldProperty.Comments.Add(new CodeCommentStatement(" <returns></returns> ", true));
                //fieldProperty.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference("DataMember")));
                fieldProperty.CustomAttributes.Add(new CodeAttributeDeclaration("FieldAttribute",
                                                                                new[]
                                                                                    {
                                                                                        new CodeAttributeArgument(
                                                                                            new CodePrimitiveExpression(
                                                                                                0))
                                                                                    }));
                fieldProperty.HasGet = true;
                fieldProperty.GetStatements.Add(new CodeMethodReturnStatement(
                                                    new CodeFieldReferenceExpression(
                                                        new CodeThisReferenceExpression(), "_" + fieldName)));

                fieldProperty.HasSet = true;
                fieldProperty.SetStatements.Add(
                    new CodeAssignStatement(
                        new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_" + fieldName),
                        new CodePropertySetValueReferenceExpression()));

                table.Members.Add(fieldProperty);
            }
            initMember += @"
           
        }
";
            thisstr += @"
                    default:
                        {
                            throw new InvalidCastException(" + "\"不存在相应的属性！\"" + @");
                        }
                }
            }
            set
            {
                ((TableFieldType)this[caption]).SetValue(value);
            }
        }
";
            table.Members.Add(new CodeSnippetTypeMember(initMember));
            table.Members.Add(new CodeSnippetTypeMember(thisstr));

            #endregion

            #region  FieldsGroup

            GroupFieldProperty groupFieldProperty;
            TableFieldGroupProperty tableFieldGroupProperty;
            op =
                @"
        public override List<RuleCode.Common.AOTFieldGroup> AOTFieldGroups
        {
            get
            {                
                this.aotFieldGroups = new List<RuleCode.Common.AOTFieldGroup>();               
                            ";
            if (node.Nodes.Count > 0)
            {
                TreeNode tempnodeFieldGroup = node.Nodes.Find("FieldGroups", false).First();
                if (tempnodeFieldGroup.Nodes.Count > 0)
                {
                    op +=
                        @"
                            RuleCode.Common.AOTFieldGroup fieldGroup  ;
                            RuleCode.Common.AOTField field  ;
                            ";
                }
                tempnodeFieldGroup.ExpandAll();
                foreach (SysTreeNode relation in tempnodeFieldGroup.Nodes)
                {


                    Util.SetPropertyInSilent = true;
                    Util.SetPropertyContent(relation);
                    Util.SetPropertyInSilent = false;
                    tableFieldGroupProperty = (TableFieldGroupProperty)relation.Property;
                    op += "                           fieldGroup = new RuleCode.Common.AOTFieldGroup();" + Environment.NewLine;
                    op += "                           fieldGroup.ID=" + "\"" + tableFieldGroupProperty.ID + "\";" + Environment.NewLine;
                    op += "                           fieldGroup.Name=" + "\"" + relation.Name + "\";" + Environment.NewLine;
                    op += "                           fieldGroup.Label=" + "\"" + tableFieldGroupProperty.Label + "\";" + Environment.NewLine;
                    relation.ExpandAll();
                    foreach (SysTreeNode fieldNode in relation.Nodes)
                    {
                        Util.SetPropertyInSilent = true;
                        Util.SetPropertyContent(fieldNode);
                        Util.SetPropertyInSilent = false;
                        groupFieldProperty = (GroupFieldProperty)fieldNode.Property;
                        op += "                           field = new RuleCode.Common.AOTField();" + Environment.NewLine;
                        op += "                           field.FieldName = " + "\"" + groupFieldProperty.DataField + "\";" + Environment.NewLine;
                        op += "                           field.FieldType =typeof (" + name + "_" + groupFieldProperty.DataField + " );" + Environment.NewLine;
                        op += "                           fieldGroup.FieldGroup.Add(field);" + Environment.NewLine;
                    }
                    op += "                           this.aotFieldGroups.Add(fieldGroup); " + Environment.NewLine;
                }
            }
            op +=
                @"
                               return this.aotFieldGroups;
                            }
                        }
                        ";
            table.Members.Add(new CodeSnippetTypeMember(op));

            #endregion

            #region 索引 TableIndex

            TableIndexFieldProperty tableIndexFieldProperty;
            TableIndexProperty tableIndexProperty;
            op =
                @"
        public override List<RuleCode.Common.AOTTableIndex> AOTTableIndexs
        {
            get
            {
                this.aotTableIndexs = new List<RuleCode.Common.AOTTableIndex>();                
                            ";
            node.ExpandAll();
            if (node.Nodes.Count > 0)
            {
                TreeNode tempnodeFieldGroup = node.Nodes.Find("Indexes", false).First();
                if (tempnodeFieldGroup.Nodes.Count > 0)
                {
                    op +=
                        @"
                            RuleCode.Common.AOTTableIndex tableIndex;
                            RuleCode.Common.AOTField field  ;
                            ";
                }
                tempnodeFieldGroup.ExpandAll();
                foreach (SysTreeNode relation in tempnodeFieldGroup.Nodes)
                {
                    Util.SetPropertyInSilent = true;
                    Util.SetPropertyContent(relation);
                    Util.SetPropertyInSilent = false;
                    tableIndexProperty = (TableIndexProperty)relation.Property;
                    op += "                            tableIndex = new RuleCode.Common.AOTTableIndex();" + Environment.NewLine;
                    op += "                            tableIndex.AllowDuplicates=" +
                          tableIndexProperty.AllowDuplicates.ToString().ToLower() + ";" + Environment.NewLine;
                    op += "                            tableIndex.Name=" + "\"" + relation.Name + "\";" + Environment.NewLine;
                    op += "                            tableIndex.Label=" + "\"" + tableIndexProperty.Label + "\";" + Environment.NewLine;
                    op += "                            tableIndex.ID=" + "\"" + tableIndexProperty.ID + "\";" + Environment.NewLine;
                    op += "                            tableIndex.Enabled=" + tableIndexProperty.Enabled.ToString().ToLower() + ";" + Environment.NewLine;

                    relation.ExpandAll();
                    foreach (SysTreeNode fieldNode in relation.Nodes)
                    {
                        Util.SetPropertyInSilent = true;
                        Util.SetPropertyContent(fieldNode);
                        Util.SetPropertyInSilent = false;
                        tableIndexFieldProperty = (TableIndexFieldProperty)fieldNode.Property;
                        op += "                            field = new RuleCode.Common.AOTField();" + Environment.NewLine;
                        op += "                            field.FieldName = " + "\"" + tableIndexFieldProperty.DataField + "\";" + Environment.NewLine;
                        op += "                            field.FieldType =typeof (" + name + "_" + tableIndexFieldProperty.DataField + " );" + Environment.NewLine;
                        op += "                            tableIndex.FieldGroup.Add(field);" + Environment.NewLine;
                    }
                    op += "                            this.aotTableIndexs.Add(tableIndex );" + Environment.NewLine;
                }
            }
            op +=
                @"
                               return this.aotTableIndexs;
                            }
                        }
                        ";
            table.Members.Add(new CodeSnippetTypeMember(op));

            #endregion

            #region Relation

            TableRelationFieldProperty tableRelationFieldProperty;
            TableRelationProperty tableRelationProperty;
            op =
                @"
        public override List<RuleCode.Common.AOTTableRelation> AOTTableRelations
        {
            get
            {
                this.aotTableRelations = new List<RuleCode.Common.AOTTableRelation>();
                
                            ";
            if (node.Nodes.Count > 0)
            {
                TreeNode tempnodeFieldGroup = node.Nodes.Find("Relations", false).First();
                if (tempnodeFieldGroup.Nodes.Count > 0)
                {
                    op +=
                        @"
                            RuleCode.Common.AOTTableRelation tableRelation;
                            RuleCode.Common.AOTField field  ;
                            RuleCode.Common.AOTField relationField  ;
                            ";
                }
                tempnodeFieldGroup.ExpandAll();
                foreach (SysTreeNode relation in tempnodeFieldGroup.Nodes)
                {
                    Util.SetPropertyInSilent = true;
                    Util.SetPropertyContent(relation);
                    Util.SetPropertyInSilent = false;
                    tableRelationProperty = (TableRelationProperty)relation.Property;
                    op += "                            tableRelation = new RuleCode.Common.AOTTableRelation();" + Environment.NewLine;
                    op += "                            tableRelation.ID=" + "\"" + tableRelationProperty.ID + "\";" + Environment.NewLine;
                    op += "                            tableRelation.Name=" + "\"" + relation.Name + "\";" + Environment.NewLine;
                    op += "                            tableRelation.Label=" + "\"" + tableRelationProperty.Label + "\";" + Environment.NewLine;
                    op += "                            tableRelation.Validate=Convert.ToBoolean(" + "\"" + tableRelationProperty.Validate + "\");" + Environment.NewLine;
                    op += "                            tableRelation.TableName=" + "\"" + tableRelationProperty.Table + "\";" + Environment.NewLine;
                    op += "                            tableRelation.TableType=typeof(" + tableRelationProperty.Table + ") ;" + Environment.NewLine;

                    relation.ExpandAll();
                    foreach (SysTreeNode fieldNode in relation.Nodes)
                    {
                        Util.SetPropertyInSilent = true;
                        Util.SetPropertyContent(fieldNode);
                        Util.SetPropertyInSilent = false;
                        tableRelationFieldProperty = (TableRelationFieldProperty)fieldNode.Property;
                        op += "                            field = new RuleCode.Common.AOTField();" + Environment.NewLine;
                        op += "                            field.FieldName = " + "\"" + tableRelationFieldProperty.Field + "\";" + Environment.NewLine;
                        op += "                            field.FieldType =typeof (" + name + "_" + tableRelationFieldProperty.Field + " );" + Environment.NewLine;
                        op += "                            relationField = new RuleCode.Common.AOTField();" + Environment.NewLine;
                        op += "                            relationField.FieldName = " + "\"" + tableRelationFieldProperty.RelatedField + "\";" + Environment.NewLine;
                        op += "                            relationField.FieldType =typeof (" + name + "_" + tableRelationFieldProperty.RelatedField + " );" + Environment.NewLine;
                        op += "                            tableRelation.Keys.Add(field, relationField);" + Environment.NewLine;
                    }
                    op += "                            this.aotTableRelations.Add(tableRelation );" + Environment.NewLine;
                }
            }
            op +=
                @"
                               return this.aotTableRelations;
                            }
                        }
                        ";
            table.Members.Add(new CodeSnippetTypeMember(op));

            #endregion

            #region DeleteAction

            TableDeleteActionProperty tableDeleteActionProperty;
            op =
                @"
        public override List<RuleCode.Common.AOTDeleteAction> AOTDeleteActions
        {
            get
            {
                this.aotDeleteActions = new List<RuleCode.Common.AOTDeleteAction>();
                            ";
            if (node.Nodes.Count > 0)
            {
                TreeNode tempnodeFieldGroup = node.Nodes.Find("DeleteActions", false).First();
                if (tempnodeFieldGroup.Nodes.Count > 0)
                {
                    op +=
                        @"
                           RuleCode.Common.AOTDeleteAction deleteAction;
                            ";
                }
                tempnodeFieldGroup.ExpandAll();
                foreach (SysTreeNode relation in tempnodeFieldGroup.Nodes)
                {
                    Util.SetPropertyInSilent = true;
                    Util.SetPropertyContent(relation);
                    Util.SetPropertyInSilent = false;
                    tableDeleteActionProperty = (TableDeleteActionProperty)relation.Property;
                    op += "                           deleteAction = new RuleCode.Common.AOTDeleteAction();" + Environment.NewLine;
                    op += "                           deleteAction.ID=" + "\"" + tableDeleteActionProperty.ID + "\";" + Environment.NewLine;
                    op += "                           deleteAction.Name=" + "\"" + relation.Name + "\";" + Environment.NewLine;
                    op += "                           deleteAction.Action=" + "\"" + tableDeleteActionProperty.DeleteAction + "\";" + Environment.NewLine;
                    op += "                           deleteAction.DeleteAction = DeleteAction." + tableDeleteActionProperty.DeleteAction + " ;" + Environment.NewLine;
                    op += "                           deleteAction .TableType =typeof (" + tableDeleteActionProperty.Table + ");" + Environment.NewLine;
                    op += "                           deleteAction.TableName=" + "\"" + tableDeleteActionProperty.Table + "\";" + Environment.NewLine;
                    op += "                           this.aotDeleteActions.Add(deleteAction); " + Environment.NewLine;
                }
            }
            op +=
                @"
                               return this.aotDeleteActions;
                            }
                        }
                        ";
            table.Members.Add(new CodeSnippetTypeMember(op));

            #endregion

            #region  Methods

            //MethodProperty methodProperty;

            //if (node.Nodes.Count > 0)
            //{
            //    TreeNode tempnodeFieldGroup = node.Nodes.Find("Methods", false).First<TreeNode>();

            //    foreach (SysTreeNode relation in tempnodeFieldGroup.Nodes)
            //    {
            //        Util.SetPropertyInSilent = true;
            //        Util.SetPropertyContent(relation);
            //        Util.SetPropertyInSilent = false;
            //        methodProperty = (MethodProperty)relation.Property;
            //        op = methodProperty.Content;
            //        table.Members.Add(new CodeSnippetTypeMember(op));
            //    }
            //}

            #endregion
            #region Partial Table Content
            string content = @"
            //按钮事件
            //static public bool Button_Method(string recid)
            //{

            //    return false;
            //}
            ////查询数据
            //protected override void OnPreFetch(RuleCode.Common.PreFetchEventArg e)
            //{
            //    base.OnPreFetch(e);
            //}
            //protected override void OnAftFetch(RuleCode.Common.AftFetchEventArg e)
            //{
            //    base.OnAftFetch(e);
            //}
            ////增加
            //protected override void OnAftNew(RuleCode.Common.AftNewEventArg e)
            //{
            //    base.OnAftNew(e);
            //}
            //protected override void OnPreInsert(RuleCode.Common.PreInsertEventArg e)
            //{
            //    base.OnPreInsert(e);
            //}
            //protected override void OnAftInsert(RuleCode.Common.AftInsertEventArg e)
            //{
            //    base.OnAftInsert(e);
            //}
            ////保存前的检验
            //protected override void OnPreValidate(RuleCode.Common.PreValidateEventArg e)
            //{
            //    base.OnPreValidate(e);
            //}
            //protected override void OnAftValidate(RuleCode.Common.AftValidateEventArg e)
            //{
            //    base.OnAftValidate(e);
            //}
            ////删除
            //protected override void OnPreDelete(RuleCode.Common.PreDeleteEventArg e)
            //{
            //    base.OnPreDelete(e);
            //}
            //protected override void OnAftDelete(RuleCode.Common.AftDeleteEventArg e)
            //{
            //    base.OnAftDelete(e);
            //}
            ////修改
            //protected override void OnPreUpdate(RuleCode.Common.PreUpdateEventArg e)
            //{
            //    base.OnPreUpdate(e);
            //}
            //protected override void OnAftUpdate(RuleCode.Common.AftUpdateEventArg e)
            //{
            //    base.OnAftUpdate(e);
            //}
            ////增加或者修改
            //protected override void OnPreModify(RuleCode.Common.PreModifyEventArg e)
            //{
            //    base.OnPreModify(e);
            //}
            //protected override void OnAftModify(RuleCode.Common.AftModifyEventArg e)
            //{
            //    base.OnAftModify(e);
            //}
            //protected override void OnError(RuleCode.Common.OnErrorArg e)
            //{
            //    base.OnError(e);
            //}";
            partialTable.Members.Add(new CodeSnippetTypeMember(content));
            #endregion

            #region 输出与编译

            //下面是编译有关的内容

            CodeGeneratorOptions options = new CodeGeneratorOptions();
            options.BlankLinesBetweenMembers = false;
            options.IndentString = "\t";
            CompilerParameters cp = new CompilerParameters();


            cp.OutputAssembly = Util.GetTablesPath + "\\" + name;// Util.OTPath + "\\Module\\Tables\\" + name;
            cp.ReferencedAssemblies.Add("System.dll");
            cp.ReferencedAssemblies.Add("System.Data.dll");
            cp.ReferencedAssemblies.Add("System.Xml.dll");
            cp.ReferencedAssemblies.Add("mscorlib.dll");
            cp.ReferencedAssemblies.Add("System.Windows.Forms.dll");
            cp.ReferencedAssemblies.Add("RuleCode.Common.dll");
            cp.ReferencedAssemblies.Add("RuleCode.ObjectTree.dll");


            cp.WarningLevel = 1;


            cp.CompilerOptions = "/target:module /optimize /moduleassemblyname:RuleCode.Table.dll";
            cp.GenerateExecutable = false;
            cp.GenerateInMemory = false;

            TempFileCollection tfc = new TempFileCollection(Path.GetTempPath(), false);

            CompilerResults cr = new CompilerResults(tfc);
            CSharpCodeProvider csp = new CSharpCodeProvider();
            DirectoryInfo dir = new DirectoryInfo(TablePath);
            if (!dir.Exists)
            {
                dir.Create();
            }
            IndentedTextWriter tw =
                new IndentedTextWriter(new StreamWriter(TablePath + node.Text + ".Designer.cs", false), "    ");
            csp.GenerateCodeFromCompileUnit(CompileUnit, tw, new CodeGeneratorOptions());

            tw.Close();

            string partialFile = PartialTablePath + node.Text + ".cs";
            if (!File.Exists(partialFile))
            {
                
                CSharpCodeProvider csp1 = new CSharpCodeProvider();
             

                IndentedTextWriter tw1 =
                    new IndentedTextWriter(new StreamWriter(partialFile, false), "    ");
                csp1.GenerateCodeFromCompileUnit(PartialCompileUnit, tw1, new CodeGeneratorOptions());

                tw1.Close();
 
            }
           



           
            //cr = csp.CompileAssemblyFromDom(cp, CompileUnit);

            //if (cr.Errors.Count > 0)
            //{
            //    foreach (CompilerError ce in cr.Errors)
            //    {
            //        Console.WriteLine(ce.ErrorNumber + ": " + ce.ErrorText);
            //    }
            //    MessageBox.Show("Errors occoured", "Errors", MessageBoxButtons.OK, MessageBoxIcon.Error);

            //}

            #endregion


            //将编译 好的文件添加到项目中
            if (Util_DTE.IsAddToProjectAtCompiled)
                Util_DTE.AddGeneratedFileToProject(node, GenerateFileType.Table);      
        }



        public void compileTables(SysTreeNode tables)
        {
            //    CompilerParameters cp = new CompilerParameters();
            //    cp.OutputAssembly = Util.OTPath + "\\Module\\Tables\\RuleCode.Table.dll";
            //    cp.ReferencedAssemblies.Add("System.dll");
            //    cp.ReferencedAssemblies.Add("System.Data.dll");
            //    cp.ReferencedAssemblies.Add("System.Xml.dll");
            //    cp.ReferencedAssemblies.Add("mscorlib.dll");
            //    cp.ReferencedAssemblies.Add("System.Windows.Forms.dll");
            //    cp.ReferencedAssemblies.Add("RuleCode.Query.Type.dll");
            //    cp.ReferencedAssemblies.Add("RuleCode.Query.Tables.dll");
            //    cp.ReferencedAssemblies.Add("RuleCode.Common.dll");
            //    cp.ReferencedAssemblies.Add("RuleCode.Query.Enum.dll");
            //    cp.WarningLevel = 3;
            tables.ExpandAll();
            //    string[] tableNames = new string[tables.GetNodeCount(false)];
            //    int i = 0;
            foreach (SysTreeNode node in tables.Nodes)
            {
                compileTable(node);
            }
            //    foreach (SysTreeNode node in tables.Nodes)
            //    {
            //        tableNames[i] = Util.OTPath + "\\Module\\Tables\\" + node.Text;
            //        i++;
            //    }
            //    string file = String.Join(",", tableNames);


            //    cp.CompilerOptions = "/target:library /optimize /addmodule:" + file;
            //    cp.GenerateExecutable = false;
            //    cp.GenerateInMemory = false;
            //    System.CodeDom.Compiler.TempFileCollection tfc = new TempFileCollection(Path.GetTempPath(), false);
            //    CompilerResults cr = new CompilerResults(tfc);
            //    CSharpCodeProvider csp = new CSharpCodeProvider();

            //    CodeCompileUnit CompileUnit = new CodeCompileUnit();
            //    cr = csp.CompileAssemblyFromDom(cp, CompileUnit);


            //    if (cr.Errors.Count > 0)
            //    {
            //        foreach (CompilerError ce in cr.Errors)
            //        {
            //            Console.WriteLine(ce.ErrorNumber + ": " + ce.ErrorText);
            //        }
            //        MessageBox.Show("Errors occoured", "Errors", MessageBoxButtons.OK, MessageBoxIcon.Error);

            //    }
            string Module = Util.OTPath_Module + "\\"; //Util.OTPath + "\\Module\\";
            //不编译DLL
            //Boolean fst = SysCompiler.CompileCSharpCode2(
            //    new[] { Module + "ExtendDataTypes", Module + "TableFields", Module + "Tables", Module + "Enums" },
            //    Util.GetLibPath + "\\RuleCode.Table.dll");
            ////编译Query
            //if (fst)
            //{
            //    Module = Util.OTPath + "\\Module\\";
            //    SysCompiler.CompileCSharpCode2(
            //        new[] { Module + "Queries" },
            //        Util.GetLibPath + "\\RuleCode.Query.dll");
            //}


        }



        //todo:create Query path
        private void compileTableQuery(string id, string tableName, string label,SysTreeNode treeNode)
        {
            if (File.Exists(QueryDemoPath))
            {
                Util.MakeSureDirectoryExistance(QueryPath);
                string newpath = QueryPath + id + ".cs";
                if (File.Exists(newpath))
                {
                    File.Delete(newpath);

                }

                File.Copy(QueryDemoPath, newpath);

                string str = "";
                StreamReader streamReader = new StreamReader(newpath, System.Text.Encoding.UTF8);

                while (streamReader.Peek() >= 0)
                {
                    str += replaceString(streamReader.ReadLine(), tableName, label) + "\r\n";
                }
                streamReader.Close();
                System.IO.File.Delete(newpath); //删除原来文件
                StreamWriter streamWriter = new StreamWriter(newpath, false, System.Text.Encoding.UTF8);
                streamWriter.Write(str);
                streamWriter.Close();
                
                //将生成好的Query添加到项目中
                Util_DTE.AddGeneratedFileToProject(treeNode, GenerateFileType.Query);
            }
        }
        //替换字符串
        private string replaceString(string _sourceString, string _formName, string _label)
        {
            string ret;
            ret = _sourceString;
            ret = ret.Replace("单表标准模块", _formName);

            ret = ret.Replace("@SYS13342", _label);
            return ret;
        }
    }
}